package com.sgb.kjwl.viewmodel.self;

import androidx.databinding.ObservableField;

import android.text.TextUtils;
import android.util.Base64;
import android.widget.Toast;





import com.sgb.kjwl.api.APIManager;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.view.ui.fragment.self.EnterpriseRegistrationFragment;
import com.sgb.kjwl.view.ui.fragment.self.PersonalRegistrationFragment;
import com.sgb.link.utils.Preferences;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterModel3 extends BaseViewModel {
  /*  public ObservableField<String> account = new ObservableField<>("");
    public ObservableField<String> pwd = new ObservableField<>("");
    public ObservableField<String> code = new ObservableField<>("");*/
    public ObservableField<Boolean> agree = new ObservableField<>(false);
    private PersonalRegistrationFragment personalRegistrationFragment;
    private EnterpriseRegistrationFragment enterpriseRegistrationFragment;
    private SelfRepertory repertory;

    public RegisterModel3(PersonalRegistrationFragment personalRegistrationFragment, SelfRepertory repertory) {
        this.personalRegistrationFragment = personalRegistrationFragment;
        this.repertory = repertory;
    }

    public RegisterModel3(EnterpriseRegistrationFragment enterpriseRegistrationFragment, SelfRepertory repertory) {
        this.enterpriseRegistrationFragment = enterpriseRegistrationFragment;
        this.repertory = repertory;
    }


    public void getCodeModel(String phone) {
        APIManager.getInstance().getUserAPI().getRegisterCode(phone).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() != null)
                    //bugly报Toast行空指针处理
                    if (personalRegistrationFragment!=null&& !TextUtils.isEmpty(response.body().getMsg())){
                        Toast.makeText(personalRegistrationFragment.getActivity(),response.body().getMsg(),Toast.LENGTH_SHORT);
                    }
                if (response.body().getState().equals("ok")) {
                    personalRegistrationFragment.getCodeSuccess();
                } else {
                    if (personalRegistrationFragment!=null&& !TextUtils.isEmpty(response.body().getMsg())){
                        MToast.showToast(personalRegistrationFragment.getActivity(), response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                if (personalRegistrationFragment!=null&& !TextUtils.isEmpty(t.getMessage())){
                    MToast.showToast(personalRegistrationFragment.getActivity(), t.getMessage());
                }
            }
        });
    }


    public void registerModel(String phone,String pwd,String code) {
        DialogHelper.showProgressDialog(personalRegistrationFragment.getActivity(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        personalRegistrationFragment.setEnable(false);
        APIManager.getInstance().getUserAPI().register(phone, android.util.Base64.encodeToString(pwd.getBytes(), Base64.DEFAULT), code,1).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                personalRegistrationFragment.setEnable(true);
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
                    MToast.showToast(personalRegistrationFragment.getActivity(), "恭喜您，注册成功！");
                    personalRegistrationFragment.loginSucceed(response.body().getData(), phone);
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, phone);
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, response.body().getData().getResourcePCToken());
                    JPushInterface.setAlias(personalRegistrationFragment.getActivity(), 1, phone);
//                    getUserInfo();
                    pwdLoginModel(phone,pwd);
                } else {
                    MToast.showToast(personalRegistrationFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                personalRegistrationFragment.setEnable(true);
                MToast.showToast(personalRegistrationFragment.getActivity(), t.getMessage());
            }
        });
    }


    public void getUserInfo() {
        personalRegistrationFragment.setEnable(false);
        DialogHelper.showProgressDialog(personalRegistrationFragment.getActivity(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                personalRegistrationFragment.setEnable(true);
                DialogHelper.dismissProgressDialog();

                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    personalRegistrationFragment.getUserMsgSucceed(response.body().getData());
                    repertory.saveNo(response.body().getData().getNo());
                    personalRegistrationFragment.showSuccessDialog();
                } else {
                    MToast.showToast(personalRegistrationFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                personalRegistrationFragment.setEnable(true);
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void pwdLoginModel(String mobile, String pwd) {
        personalRegistrationFragment.setEnable(false);
        DialogHelper.showProgressDialog(personalRegistrationFragment.getActivity(), null, "登录中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getUserAPI().login(mobile, Base64.encodeToString(pwd.getBytes(), Base64.DEFAULT)).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {
                personalRegistrationFragment.setEnable(true);
                if (response.body() == null) return;

                if (response.body().getState().equals("ok")) {
//                    saveUserInfo(response.body().getData());
//                    repertory.saveAccount(mobile);
//                    MToast.showToast(activity, "登录成功");
//                    activity.loginSucceed(response.body().getData(), mobile);
//                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
//                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, mobile);
//                    JPushInterface.setAlias(activity, 1, mobile);
//                    getUserInfo();
                    loginImModel(response, mobile);
                } else {
                    DialogHelper.dismissProgressDialog();
                    MToast.showToast(personalRegistrationFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                personalRegistrationFragment.setEnable(true);
                DialogHelper.dismissProgressDialog();
                MToast.showToast(personalRegistrationFragment.getActivity(), t.getMessage());
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response, String mobile) {
        personalRegistrationFragment.setEnable(false);
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, response.body().getData().getResourcePCToken());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, response.body().getData().getResourceAPPToken());

//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                personalRegistrationFragment.setEnable(true);
                saveUserInfo(response.body().getData());
                repertory.saveAccount(mobile);
//                MToast.showToast(activity, "登录成功");
                if (personalRegistrationFragment != null && personalRegistrationFragment.getActivity() != null){
                    Toast.makeText(personalRegistrationFragment.getActivity(),"登录成功",Toast.LENGTH_SHORT).show();
                }
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, mobile);
                personalRegistrationFragment.loginSucceed(response.body().getData(), mobile);
                JPushInterface.setAlias(personalRegistrationFragment.getActivity().getApplicationContext(), 1, mobile);
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                personalRegistrationFragment.setEnable(true);
//                DialogHelper.dismissProgressDialog();
////                MToast.showToast(activity, "账号信息异常,请联系管理员!");
//                Toast.makeText(personalRegistrationFragment.getActivity().getApplicationContext(),"账号信息异常,请联系管理员!",Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                personalRegistrationFragment.setEnable(true);
//                DialogHelper.dismissProgressDialog();
////                MToast.showToast(activity, "账号信息异常,请联系管理员!");
//                Toast.makeText(personalRegistrationFragment.getActivity().getApplicationContext(),"账号信息异常,请联系管理员!",Toast.LENGTH_SHORT).show();
//            }
//        });
    }
    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }
}
